<template>
    <div class="e-form">
        <div class="tabs" v-if="Object.keys(formData).length != 0">
             <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
                 <!-- 基本信息 -->
                <el-tab-pane label="设备信息" name="equipInfo" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="基础价格" name="basePrice" :disabled="clickTabFlag"></el-tab-pane>
                <div>
                    <div id="equipInfoCon">
                        <div class="tabs-title" id="equipInfo">设备信息</div>
                        <div style="width: 100%" class="form">
                            <el-form ref="form" :model="formData" :rules="rulesBase" label-width="200px">
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="设备名称：" prop="equipmentName">
                                            <el-input
                                                placeholder="请输入内容"
                                                v-model="formData.equipmentName"
                                                clearable>
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="计量单位：">
                                            <el-select
                                                v-model="formData.unit"
                                                placeholder="请选择"
                                            >
                                                <el-option
                                                    v-for="(
                                                        item, index
                                                    ) in unitMeasure"
                                                    :key="index"
                                                    :label="item.label"
                                                    :value="item.value"
                                                >
                                                </el-option>
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="设备状态：" prop="state">
                                            <el-select
                                                v-model="formData.state"
                                                placeholder="请选择"
                                            >
                                                <el-option
                                                    v-for="(
                                                        item, index
                                                    ) in stateList"
                                                    :key="index"
                                                    :label="item.label"
                                                    :value="item.value"
                                                >
                                                </el-option>
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="设备分类：">
                                            <span>{{ formData.categoryName }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="录入日期：">
                                            <span>{{ formData.gmtCreate }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="录入人：">
                                            <span>{{ formData.recorder }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="最后修改人：">
                                            <span>{{ formData.modifier }}</span>
                                        </el-form-item>
                                    </el-col>
                                <el-col :span="12">
                                        <el-form-item label="最后修改时间：">
                                            <span>{{ formData.gmtModified }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-form-item  label="价格备注：">
                                        <el-input type="textarea" v-model="formData.remarks"></el-input>
                                    </el-form-item>
                                </el-row>
                            </el-form>
                        </div>
                    </div>

                    <div id="basePriceCon">
                        <div class="tabs-title" id="basePrice">基础价格</div>
                        <div style="width: 100%" class="form">
                            <el-form ref="priceForm" :model="formData" :rules="rules"  label-width="200px">
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="市场采购价：" prop="marketBuyPrice">
                                            <el-input
                                                placeholder="请输入内容"
                                                v-model="formData.marketBuyPrice"
                                                v-enterJustFloat
                                            >
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="市场租赁价：" prop="marketLeasePrice">
                                            <el-input
                                                placeholder="请输入内容"
                                                v-model="formData.marketLeasePrice"
                                                v-enterJustFloat
                                            >
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="指导采购价：" prop="guidanceBuyPrice">
                                            <el-input
                                                placeholder="请输入内容"
                                                v-model="formData.guidanceBuyPrice"
                                                v-enterJustFloat
                                            >
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="指导租赁价：" prop="guidanceLeasePrice">
                                            <el-input
                                                placeholder="请输入内容"
                                                v-model="formData.guidanceLeasePrice"
                                                v-enterJustFloat
                                            >
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="内部调拨价：" prop="innerAllocationPrice">
                                            <el-input
                                                placeholder="请输入内容"
                                                v-model="formData.innerAllocationPrice"
                                                v-enterJustFloat
                                            >
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </div>
                    </div>
                </div>
            </el-tabs>
        </div>
         <div class="buttons">
            <el-button
                type="primary"
                size="small"
                class="btn-blue"
                @click="preserve"
            >保存</el-button>
            <el-button
                type="primary"
                size="small"
                class="btn-red"
                @click="onDel"
            >删除</el-button>
            <el-button size="small" @click="handleClose">取消</el-button>
        </div>
        <div id="seat" :style="{height: seatHeight + 'px'}"></div>
    </div>
</template>

<script>
import { mapState } from 'vuex'
import $ from 'jquery'
import '@/utils/jquery.scrollTo.min'
import { formatDate } from '@/utils/common.js'
export default {
    data () {
        return {
            tabsName: 'equipInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            formData: {
            },
            stateList: [
                {
                    label: '停用',
                    value: 0
                },
                {
                    label: '启用',
                    value: 1
                },
            ], //设备状态
            rulesBase: {
                equipmentName: [
                    { required: true, message: '请输入设备名称', trigger: 'blur' },
                ],
                state: [
                    { required: true, message: '请输入设备启用状态', trigger: 'blur' },
                ],
            },
            rules: {
                guidanceBuyPrice: [
                    { required: true, message: '请输入指导采购价', trigger: 'blur' },
                ],
                guidanceLeasePrice: [
                    { required: true, message: '请输入指导租赁价', trigger: 'blur' },
                ],
                innerAllocationPrice: [
                    { required: true, message: '请输入内部调拨价', trigger: 'blur' },
                ],
                marketBuyPrice: [
                    { required: true, message: '请输入市场采购价', trigger: 'blur' },
                ],
                marketLeasePrice: [
                    { required: true, message: '请输入市场租赁价', trigger: 'blur' },
                ]
            },
        }
    },
    props: {
        categoryId: {
            type: String,
            default: ''
        },
        categoryName: {
            type: String,
            default: ''
        },
        isEdit: {
            type: String,
            default: ''
        },
        equipData: {
            type: Object,
            default: ()=>{}
        }
    },
    computed: {
        ...mapState({
            userInfo: state => state.userInfo,
            unitMeasure: state => state.equip.equipData.unitMeasure//计量单位
        }),
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        }
    },
    components: {
    },
    created () {
        this.userId = localStorage.getItem('userId')
        this.userName = localStorage.getItem('userName')
        if(this.isEdit === 'add') {
            this.formData = {
                'categoryId': '',
                'equipmentId': '',
                'equipmentName': '',
                'founderId': '',
                'founderName': '',
                'gmtCreate': '',
                'gmtModified': '',
                'guidanceBuyPrice': 0,
                'guidanceLeasePrice': 0,
                'innerAllocationPrice': 0,
                'isUsed': '',
                'marketBuyPrice': 0,
                'marketLeasePrice': 0,
                'modifier': '',
                'modifierId': '',
                'oneLevelCategoryId': '',
                'oneLevelCategoryName': '',
                'recorder': '',
                'recorderId': '',
                'specificationModel': '',
                'state': '',
                'unit': '',
                'workId': ''
            }
            let date  = formatDate(new Date(), 'yyyy-MM-dd')
            this.formData.unit = this.unitMeasure[0].value
            this.formData.gmtCreate = date
            this.formData.recorder = this.userName
            this.formData.categoryId = this.categoryId
            this.formData.categoryName = this.categoryName
        }
        else if(this.isEdit === 'edit') {
            this.formData = this.equipData
        }
        this.getDicValue()
    },
    mounted () {
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = ['equipInfo', 'basePrice']
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    console.log('item', item)
                    const itemTop = document.getElementById(item).offsetTop
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if ((scrollTop + 1) >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth
        this.screenHeight = document.documentElement.clientHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth
            this.screenHeight = document.documentElement.clientHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
    },
    methods: {
        //获取当前使用的字典
        getDicValue () {
            this.$store.dispatch('equip/setUnitMeasur')//更新计量单位
        },
        //保存
        preserve () {
            this.$refs.form.validate(validBase=>{
                if(validBase) {
                    this.$refs.priceForm.validate(valid=>{
                        if(valid) {
                            this.$emit('cancel', this.formData)
                        }
                    })
                }
            })
        },
        onDel () {
            this.$emit('del', this.formData)
        },
        //取消
        handleClose () {
            this.$emit('onCancel')
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('recodesCon')) {
                    const lastConHeight = document.getElementById('recodesCon').offsetHeight
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        onChangeTab (e) {
            $.scrollTo(`#${e.name}`, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
    }
}
</script>

<style lang="scss" scoped>
.form {
    margin-top: 10px;
}

.e-table {
    background: #fff;

    /* .top {
    .left {
      padding: 20px;
      padding-top: 0px;
    }
  } */
}

.upload {
    margin: 20px auto;
    display: flex;
    justify-content: center;
    text-align: center;
}

.upload-demo {
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>
